// include/sensor_data_subscriber.h
#ifndef SENSOR_DATA_SUBSCRIBER_H
#define SENSOR_DATA_SUBSCRIBER_H

#include <QObject>
#include <QThread>
#include <atomic>
#include <rclcpp/rclcpp.hpp>
#include "rms_pkg/msg/sensor_data.hpp" 

class SensorDataWorker;

class SensorDataSubscriber : public QObject
{
    Q_OBJECT

public:
    explicit SensorDataSubscriber(QObject *parent = nullptr);
    ~SensorDataSubscriber();

    // 启动和停止订阅器
    void start();
    void stop();
    
    // 设置机器人ID并重新订阅话题
    Q_INVOKABLE void setNamespace(const QString &robotId);

signals:
    // 当接收到传感器数据时发出信号，包含robot_id
    void sensorDataUpdated(const QString &robotId,
                          const QString &airTemperature,
                          const QString &airHumidity,
                          const QString &lightIntensity,
                          const QString &co2Concentration,
                          const QString &soilTemperature,
                          const QString &soilMoisture);

private:
    SensorDataWorker* worker_;
    QThread workerThread_;
};

// 工作者类，在独立线程中运行
class SensorDataWorker : public QObject
{
    Q_OBJECT

public:
    explicit SensorDataWorker(QObject *parent = nullptr);
    ~SensorDataWorker();

    void setNamespace(const QString &robotId);

public slots:
    void start();
    void stop();

signals:
    void sensorDataUpdated(const QString &robotId,
                          const QString &airTemperature,
                          const QString &airHumidity,
                          const QString &lightIntensity,
                          const QString &co2Concentration,
                          const QString &soilTemperature,
                          const QString &soilMoisture);
    void finished();

private:
    void run();
    void subscribeTopic();

private:
    const std::string NODE_NAME = "env_sensor_subscriber";
    std::shared_ptr<rclcpp::Node> node_;
    rclcpp::Subscription<rms_pkg::msg::SensorData>::SharedPtr subscription_;
    std::shared_ptr<rclcpp::executors::SingleThreadedExecutor> executor_;
    std::atomic<bool> running_;
    std::string robotId_;
};

#endif // SENSOR_DATA_SUBSCRIBER_H